import java.util.Arrays;
import java.util.Comparator;

public class MergeIntervals {
    public int[][] mergeIntervals(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]==o2[0]?o1[1]-o2[1]:o1[0]-o2[0];
            }
        });
        int i=0,j=0;
        while (++j < intervals.length) {
            if(intervals[i][1]>=intervals[j][0]){
                intervals[i][1]=Math.max(intervals[i][1],intervals[j][1]);
            }else{
                intervals[++i]=intervals[j];
            }
        }
        return Arrays.copyOf(intervals,i+1);

    }
}
